<template>
  <a-spin :loading="loading" style="width: 100%">
    <a-card
      class="general-card"
      :header-style="{ paddingBottom: 0 }"
      :body-style="{
        paddingTop: '20px',
      }"
    >
      <template #title>
        <h2>人体数据指标检查</h2>
      </template>
      <template #extra>
        <a-select :style="{ width: '320px' }" placeholder="请选择检验数据指标">
          <a-option>白细胞</a-option>
          <a-option>红细胞</a-option>
          <a-option>血小板</a-option>
          <a-option disabled>肝功能</a-option>
        </a-select>
      </template>
      <div class="timeBox">
        <h3>白细胞数据指标</h3>
        <a-range-picker />
      </div>
      <Chart height="289px" :option="chartOption" />
    </a-card>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, watch } from 'vue';
  import { graphic } from 'echarts';
  import useLoading from '@/hooks/loading';
  import { queryContentData, ContentDataRecord } from '@/api/dashboard';
  import useChartOption from '@/hooks/chart-option';
  import { ToolTipFormatterParams } from '@/types/echarts';
  import { AnyObject } from '@/types/global';

  // 接收父组件传递的患者数据
  const props = defineProps({
    patientData: {
      type: Object,
      default: () => ({})
    }
  });

  function graphicFactory(side: AnyObject) {
    return {
      type: 'text',
      bottom: '8',
      ...side,
      style: {
        text: '',
        textAlign: 'center',
        fill: '#4E5969',
        fontSize: 12,
      },
    };
  }
  const { loading, setLoading } = useLoading(true);
  const xAxis = ref<string[]>([]);
  const chartsData = ref<number[]>([]);
  const graphicElements = ref([
    graphicFactory({ left: '2.6%' }),
    graphicFactory({ right: 0 }),
  ]);
  const { chartOption } = useChartOption(() => {
    return {
      grid: {
        left: '2.6%',
        right: '0',
        top: '10',
        bottom: '30',
      },
      xAxis: {
        type: 'category',
        offset: 2,
        data: xAxis.value,
        boundaryGap: false,
        axisLabel: {
          color: '#4E5969',
          formatter(value: number, idx: number) {
            if (idx === 0) return '';
            if (idx === xAxis.value.length - 1) return '';
            return `${value}`;
          },
        },
        axisLine: {
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: true,
          interval: (idx: number) => {
            if (idx === 0) return false;
            if (idx === xAxis.value.length - 1) return false;
            return true;
          },
          lineStyle: {
            color: '#E5E8EF',
          },
        },
        axisPointer: {
          show: true,
          lineStyle: {
            color: '#23ADFF',
            width: 2,
          },
        },
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false,
        },
        axisLabel: {
          formatter(value: any, idx: number) {
            if (idx === 0) return value;
            return `${value}k`;
          },
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#E5E8EF',
          },
        },
      },
      tooltip: {
        trigger: 'axis',
        formatter(params) {
          const [firstElement] = params as ToolTipFormatterParams[];
          return `<div>
            <p class="tooltip-title">${firstElement.axisValueLabel}</p>
            <div class="content-panel"><span>总内容量</span><span class="tooltip-value">${(
              Number(firstElement.value) * 10000
            ).toLocaleString()}</span></div>
          </div>`;
        },
        className: 'echarts-tooltip-diy',
      },
      graphic: {
        elements: graphicElements.value,
      },
      series: [
        {
          data: chartsData.value,
          type: 'line',
          smooth: true,
          // symbol: 'circle',
          symbolSize: 12,
          emphasis: {
            focus: 'series',
            itemStyle: {
              borderWidth: 2,
            },
          },
          lineStyle: {
            width: 3,
            color: new graphic.LinearGradient(0, 0, 1, 0, [
              {
                offset: 0,
                color: 'rgba(30, 231, 255, 1)',
              },
              {
                offset: 0.5,
                color: 'rgba(36, 154, 255, 1)',
              },
              {
                offset: 1,
                color: 'rgba(111, 66, 251, 1)',
              },
            ]),
          },
          showSymbol: false,
          areaStyle: {
            opacity: 0.8,
            color: new graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: 'rgba(17, 126, 255, 0.16)',
              },
              {
                offset: 1,
                color: 'rgba(17, 128, 255, 0)',
              },
            ]),
          },
        },
      ],
    };
  });
  
  // 模拟根据患者ID获取不同的数据
  const fetchData = async (patientId?: number) => {
    setLoading(true);
    try {
      // 清空之前的数据
      xAxis.value = [];
      chartsData.value = [];
      
      // 这里应该根据患者ID调用不同的API，现在我们模拟不同的数据
      let chartData: ContentDataRecord[] = [];
      
      if (patientId === 111) {
        // 模拟患者1的数据
        chartData = [
          { x: '00:00', y: 8 },
          { x: '04:00', y: 9 },
          { x: '08:00', y: 7 },
          { x: '12:00', y: 10 },
          { x: '16:00', y: 8 },
          { x: '20:00', y: 9 },
          { x: '24:00', y: 7 }
        ];
      } else if (patientId === 222) {
        // 模拟患者2的数据
        chartData = [
          { x: '00:00', y: 6 },
          { x: '04:00', y: 7 },
          { x: '08:00', y: 8 },
          { x: '12:00', y: 6 },
          { x: '16:00', y: 7 },
          { x: '20:00', y: 8 },
          { x: '24:00', y: 9 }
        ];
      } else {
        // 默认数据或调用API获取数据
        const response = await queryContentData();
        chartData = response.data;
      }
      
      chartData.forEach((el: ContentDataRecord, idx: number) => {
        xAxis.value.push(el.x);
        chartsData.value.push(el.y);
        if (idx === 0) {
          graphicElements.value[0].style.text = el.x;
        }
        if (idx === chartData.length - 1) {
          graphicElements.value[1].style.text = el.x;
        }
      });
    } catch (err) {
      // you can report use errorHandler or other
      console.error('获取图表数据失败:', err);
    } finally {
      setLoading(false);
    }
  };
  
  // 监听患者数据变化，更新图表
  watch(() => props.patientData, (newVal) => {
    console.log('患者数据变化:', newVal);
    if (newVal && newVal.id) {
      fetchData(newVal.id);
    } else {
      // 如果没有患者数据，加载默认数据
      fetchData();
    }
  }, { immediate: true, deep: true });
</script>

<style scoped lang="less">
  .timeBox {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>